//
//  MainViewController.swift
//  Weibo10
//
//  Created by male on 15/10/14.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    /// MARK: - 监听方法
    @objc private func clickComposedButton() {
        //print("点我了")
        
        // 判断用户是否登录
        var vc: UIViewController
        if UserAccountViewModel.sharedUserAccount.userLogon {
            vc = ComposeViewController()
        }else {
            vc = OAuthViewController()
        }
        
        let nav = UINavigationController(rootViewController: vc)
        
        presentViewController(nav, animated: true, completion: nil)
    }
    /// MARK: - 视图的生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewControllers()
        
        setupComposedButton()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.bringSubviewToFront(composedButton)
    }
    
    /// MARK: - 懒记载控件
    private lazy var composedButton: UIButton = UIButton(
        imageName: "tabbar_compose_icon_add",
        backImageName: "tabbar_compose_button")}


//MARK: - 设置界面(函数的重载)
extension MainViewController {
    ///设置撰写按钮
    private func setupComposedButton() {
        
        tabBar.addSubview(composedButton)
        
        let count = childViewControllers.count
        
        let w = tabBar.bounds.width / CGFloat(count) - 1
        
        composedButton.frame = CGRectInset(tabBar.bounds,2 * w, 0)
    
        composedButton.addTarget(self, action: "clickComposedButton", forControlEvents: .TouchUpInside)
    }
    
    ///添加所有的控制器(多态)
    private func addChildViewControllers() {
        
        //设置 tintColor -图片渲染颜色（不用系统的）(全局外设置)
       // tabBar.tintColor = UIColor.orangeColor()
        
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        
        addChildViewController(UIViewController())
        
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
        
    }
    
    ///添的控制器
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        
        vc.title = title
        
        vc.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    
    
    
    }
}
